﻿using IOP.Orleans.MessageHub;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Test.Shared;
using Newtonsoft.Json;

namespace SimplePublishClient
{
    public class PublishHostService : IHostedService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<PublishHostService> _Logger;
        /// <summary>
        /// 消息服务
        /// </summary>
        private readonly IMessageHubService _MessageHubService;

        public PublishHostService(ILogger<PublishHostService> logger, IMessageHubService hubService)
        {
            _Logger = logger;
            _MessageHubService = hubService;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.Factory.StartNew(async () =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    TestMessage test = new TestMessage { A = 123, B = "Hello, I'm a Publisher, I send a Message" };
                    byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(test));
                    _Logger.LogInformation($"Send a Message : {test.B}");
                    try
                    {
                        await _MessageHubService.PublishMessage(data, "Hello");
                    }
                    catch (Exception e)
                    {
                        _Logger.LogError(e, e.Message);
                    }
                    await Task.Delay(5000);
                }
            }, cancellationToken);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
